wx.onMessage(data => {

  // 获取离屏画布
  let sharedCanvas = wx.getSharedCanvas()
  let ctx = sharedCanvas.getContext('2d')
  
  // 获取屏幕大小
  let CANVAS_WIDTH = sharedCanvas.width
  let CANVAS_HEIGHT = sharedCanvas.height

  // 清空离屏画布
  ctx.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT)
  
  // 如果前端发送的event是 readFriendData
  if (data.event == "readFriendData"){
    wx.getFriendCloudStorage({
      keyList: ['score'],
      success: res => { // {errMsg: "getFriendCloudStorage:ok", data: Array(0)}
        if (res.errMsg == "getFriendCloudStorage:ok"){
          // 获取用户数量
          var friendsCount = res.data.length
          // 比较函数 （按照得分）
          var compare = function (obj1, obj2) {
            var val1 = parseInt(obj1.KVDataList[0].value);
            var val2 = parseInt(obj2.KVDataList[0].value);
            if (val1 < val2) {
              return 1;
            } else if (val1 > val2) {
              return -1;
            } else {
              return 0;
            }
          } 

          var margin = (CANVAS_WIDTH - 320) / 2

          // 绘制透明图层
          var globalAlphaCanvas = wx.createCanvas()
          var globalAlphaCTX = globalAlphaCanvas.getContext('2d')
          globalAlphaCTX.globalAlpha = 0.5
          globalAlphaCTX.fillStyle = "#4c4d4d"
          globalAlphaCTX.fillRect(margin, 35, 320, 445)
          // 将透明图层绘制到 sharedCanvas
          ctx.drawImage(globalAlphaCanvas,0,0)


          // 绘制排行大标题
          ctx.fillStyle = "#87bac1"
          ctx.font = "23px STHeiti"
          ctx.fillText("好友排行榜" + "(" + friendsCount+")", (CANVAS_WIDTH - 130) / 2, 70)


          // 按照分数高低排序后截取前十位
          var y = 68 // 第1名的初始位置
          var rank = 1 // 排行名次
          var tempRankCanvas = wx.createCanvas()
          var tempRankCtx = tempRankCanvas.getContext('2d')
          tempRankCtx.fillStyle = "#FFFFFF"
          tempRankCtx.font = "16px STHeiti Light";

          res.data.sort(compare).slice(0, 8).forEach((tempdata) => {
            // 每名好友的y 坐标+50
            y = y+50
            // 昵称
            var nickname = tempdata.nickname
            // openid
            var openid = tempdata.openid
            // 头像url
            var avatarUrl = tempdata.avatarUrl
            // 得分数据（score）
            var KVDataList = tempdata.KVDataList
            var score = KVDataList[0].value

            // 昵称超过长度判断
            var lengthTemp = 0
            var showNickName = ''
            for (var i = 0;i<nickname.length;i++){
              var str = nickname.substring(i, i+1)
              // 如果是字母
              if (/^[a-zA-Z]*$/.test(str)) {  
                lengthTemp = lengthTemp + 1
              }
              else if (/^[\u4e00-\u9fa5]*$/.test(str)) {
                lengthTemp = lengthTemp + 2
              }else{
                lengthTemp = lengthTemp + 1
              }
              if (lengthTemp < 16){
                showNickName = showNickName + str
              }else{
                nickname = showNickName+'...'
                break
              }
            }

            // 绘制头像
            var image = wx.createImage()
            image.src = avatarUrl
            tempRankCtx.drawImage(image, margin + 50, y - 26, 40, 40)

            // 绘制名词昵称和得分
            if (rank == 1) {
              tempRankCtx.font = "36px Edwardian Script ITC"
              tempRankCtx.fillStyle = "#c74c51"
            } else if (rank == 2) {
              tempRankCtx.font = "30px Edwardian Script ITC"
              tempRankCtx.fillStyle = "#24a061"
            } if (rank == 3) {
              tempRankCtx.font = "24px Edwardian Script ITC"
              tempRankCtx.fillStyle = "#fd9727"
            }
            tempRankCtx.fillText(rank, margin + 15, y)
            // 切换为白色
            tempRankCtx.font = "16px STHeiti Light";
            tempRankCtx.fillStyle = "#FFFFFF"
            tempRankCtx.fillText(nickname + "  ", margin + 110, y)
            tempRankCtx.fillText(score, margin + 260, y)

            rank++
          })
          // 遍历完后，将 tempCanvas 绘制到 sharedCanvas
          ctx.drawImage(tempRankCanvas, 0, 0)
        }else{
          console.log(res.errMsg)
        }
      },
      fail: res => {
        console.log('fail' + JSON.stringify(res))
      },
    })



    
  }else if(data.event == "write"){

    // 先读取之前的数据
    wx.getUserCloudStorage({
      keyList: ["score"],
      success: res => {
        console.log('写前获取用户数据成功')
        if (res.KVDataList.length == 0) {
          wx.setUserCloudStorage({
            KVDataList: data.KvDataList,
            success: res => {
              console.log('新用户写入数据成功！' + JSON.stringify(res))
            },
            fail: res => {

            },
            complete: res => {

            },
          })

        } else if (res.KVDataList.length != 0) {
          // 如果这一次得分大于之前的数据，写数据
          var newscore = data.KvDataList[0].value
          var oldscore = res.KVDataList[0].value

          if (parseInt(newscore) > parseInt(oldscore)) {

            wx.setUserCloudStorage({
              KVDataList: data.KvDataList,
              success: res => {
                console.log('覆盖写入数据成功！' + res)
              },
              fail: res => {

              },
              complete: res => {

              },
            })
            return;
          }else{
            return;
          }

        }
        return;
      },
      fail: res => {
        console.log('fail' + JSON.stringify(res))
      },
    })

  } 
  
  
  // else if (data.event == "removeUserData") { /
  //   wx.removeUserCloudStorage({
  //     KVDataList: data.KvDataString,
  //     success: res => {
  //       console.log('移除用户数据成功')

  //     },
  //     fail: res => {

  //     },
  //     complete: res => {

  //     },
  //   })
  // } else if (data.event == "readUserData") { 
  //   wx.getUserCloudStorage({
  //     keyList: data.KvDataString,
  //     success: res => { 

  //       console.log('获取用户数据成功')
  //       // var obj = res.KVDataList[0].value
  //       // console.log(obj)
  //       return;
  //     },
  //     fail: res => {
  //       console.log('fail' + JSON.stringify(res))
  //     },
  //   })
  // }
  
})

